#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------
# -- 文件转换
# --
# ****************************
# Author: lmay.Zhou
# Blog: www.lmaye.com
# Date: 2021/3/4 14:03
# Email lmay@lmaye.com
# ----------------------------------------------------------
import math
import os
import threading
import time

from constant.sys_enum import SysEnum
from core import LOG
from utils import eml_utils, excel_utils


def handler_thread(_file_names, lens=50000):
    threads_ = []
    for i in range(math.ceil(len(_file_names) / lens)):
        records = _file_names[i * lens:(i + 1) * lens]
        thread = threading.Thread(target=write_file, args=(i, records))
        threads_.append(thread)
    return threads_


def write_file(i, _file_names):
    LOG.info("线程[{}]执行中...[{}] - [{}]".format(i + 1, threading.currentThread().name, threading.currentThread().ident))
    records = []
    for file_name in _file_names:
        records.append(eml_utils.read_eml(eml_path + file_name))
    header = ["subject", "from", "to", "content"]
    csv_path = path + "csv" + SysEnum.SEPARATOR.value
    excel_utils.write_csv(csv_path + str(round(time.time() * 1000)) + str(i) + ".csv", header, records)


if __name__ == "__main__":
    path = SysEnum.RESOURCES_PATH.value + SysEnum.SEPARATOR.value
    eml_path = path + "eml" + SysEnum.SEPARATOR.value
    file_names = os.listdir(eml_path)
    # 1. 单线程
    # records = []
    # header = ["subject", "from", "to", "content"]
    # csv_path = path + "csv" + SysEnum.SEPARATOR.value
    # for file_name in file_names:
    #     records.append(eml_utils.read_eml(eml_path + file_name))
    #     if 2 == len(records):
    #         excel_utils.write_csv(csv_path + str(round(time.time() * 1000)) + ".csv", header, records)
    #         records.clear()
    # # 剩余的处理
    # excel_utils.write_csv(csv_path + str(round(time.time() * 1000)) + ".csv", header, records)

    # 2. 多线程
    threads = handler_thread(file_names)
    for t in threads:
        t.start()
    for t in threads:
        t.join()
